﻿Imports System.Net
Imports System.Net.Sockets
Imports System.Threading.Tasks

Module Module1

    Sub Main()

        Console.WriteLine("Enter hostname:")
        Dim host As IPHostEntry = Dns.GetHostEntry(Console.ReadLine())

        Dim IP As IPAddress() = host.AddressList

        Console.WriteLine("Please enter starting port:")
        Dim StartPort As Integer = Console.ReadLine
        Console.WriteLine("Please enter end port:")
        Dim EndPort As Integer = Console.ReadLine()
        Dim OpenPort As Boolean = False

        Console.WriteLine()
        Console.WriteLine("Scanning ports " & StartPort & " to " & EndPort & " for " & host.HostName & "(" & IP(0).ToString & "), please wait...")
        Console.WriteLine()

        Try
            'Attempt to connect to each port asynchronously to reduce time the app takes to execute as a whole.
            Parallel.For(StartPort, EndPort + 1, Sub(i)
                                                     Dim TCP As New TcpClient
                                                     Dim Connected As Boolean = False

                                                     Try
                                                         TCP.Connect(IP(0), i)

                                                         If TCP.Connected Then
                                                             Connected = True
                                                         Else
                                                             Connected = False
                                                         End If

                                                     Catch ex As Exception
                                                         Connected = False
                                                     End Try

                                                     If Connected Then
                                                         Console.WriteLine("Port " & i & " is open")
                                                     Else
                                                         Console.WriteLine("Port " & i & " is closed")
                                                     End If
                                                 End Sub)


        Catch ex As Exception
            Console.WriteLine(vbCrLf & "Error: " & ex.Message)
        End Try

        Console.WriteLine(vbCrLf & "All ports have been scanned!")
        Console.ReadLine()

    End Sub

End Module
